/*
 * Created by Jaren at 2022/5/5 16:01
 */
import 'dart:async';
import 'dart:io';

import 'package:inmotion_protocol/base/base_message.dart';
import 'package:inmotion_protocol/base/protocol.dart';
import 'package:inmotion_protocol/common/file.dart' as protocol_file;
import 'package:inmotion_protocol/common/media_file_upload_manager.dart';
import 'package:inmotion_protocol/lorin/file/browse_file_method.dart';
import 'package:inmotion_protocol/lorin/file/lorin_file.dart';
import 'package:inmotion_protocol/lorin/file/lorin_file_manager.dart';

class LorinLightEffectFileUploadManager extends LightEffectPkgFileUploadManager {

    LorinLightEffectFileUploadManager(Protocol<IMessage> protocol) : super(protocol);


    @override
    Future<bool> clearCacheFiles() {
        return protocol.getFileList(filter: BrowseFileMethodBuilder().fileOnly().depthCurrentDir().fileType('tmp').withPath('0:/light').build()).then((rsp) {
            if (!rsp.isSuccess()) {
                return false;
            }
            List<protocol_file.File> tmpFiles = [];
            List<protocol_file.File> files = rsp.files;
            for (protocol_file.File file in files) {
                file as LorinFile;
                if (file.isDirectory() || file.name == '') continue;
                if (file.name.toUpperCase().endsWith("TMP")) {
                    tmpFiles.add(file);
                }
            }
            if (tmpFiles.isEmpty) {
                return false;
            }

            for (protocol_file.File file in tmpFiles) {
                deleteFile((file as LorinFile).getAbsolutePath());
            }
            return true;
        });
    }

    void deleteFile(String filePath) async {
        await protocol.deleteFile(filePath);
    }

    @override
    Future renameFileIfNeed(int id, StreamController<UploadEvent> streamController) {
        MediaUploadConfig config = getConfig!;
        String filePath = (config as LorinFileManagerConfig).remoteFilename;
        String newFilePath = filePath.substring(0, filePath.length - 3) + "rgb";
        return protocol.renameFile(filePath, newFilePath);
    }

    @override
    MediaUploadConfig createConfig(File localFile, int pkgId) {
        return LorinLightEffectFileConfig.create(fileOperationTargetDevice(), localFile, pkgId);
    }
}


class LorinLightEffectFileConfig extends LorinFileManagerConfig implements MediaUploadConfig {

    @override
    int id;

    LorinLightEffectFileConfig(int target, int openType, String remoteFilename, File localFile, this.id) : super(target, openType, remoteFilename, localFile);

    static LorinLightEffectFileConfig create(int target, File localFile, int pkgId) {
        return LorinLightEffectFileConfig(target, 2, "0:/light/diy/$pkgId.tmp", localFile, pkgId);
    }


}